package cn.mulanbay.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * 限流规则配置
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@Configuration
public class KeyResolverConfiguration {

    /**
     * 路径规则限制
     *
     * @return
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getURI().getPath());
    }

    /**
     * 参数限流：key-resolver: "#{@parameterKeyResolver}"
     *
     * @return
     */
    //@Bean
    public KeyResolver parameterKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }

    /**
     * IP限流：key-resolver: "#{@ipKeyResolver}"
     *
     * @return
     */
    //@Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
